package com.czl.elm.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czl.elm.dao.EstimateMapper;
import com.czl.elm.domain.Estimate;
import com.czl.elm.domain.UsersLoginParam;
import com.czl.elm.service.IEstimateService;
import com.czl.elm.util.ActionResult;
import com.czl.elm.util.FileUtil;
import com.czl.elm.util.RespPageBean;
import com.czl.elm.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EstimateSeviceImpl implements IEstimateService {
    @Autowired
    private EstimateMapper estimateMapper;

    @Value("${file.upload.url}")
    private String uploadFilePath;


    @Override
    @Transactional(rollbackFor=Exception.class)
    public ActionResult addEstimate(MultipartFile[] photoList, String orderId, Integer score, Integer integral, String content, Integer anonymous, String foodRecommond) {
        List<String> photoListName= null;
        if (photoList != null && photoList.length >= 1) {
            photoListName= new ArrayList<>();
            int index = 0;
            for (MultipartFile profile : photoList) {
                String filetype = profile.getOriginalFilename().split("\\.")[1];
                if (!FileUtil.imgCheck(filetype)) {
                    return ActionResult.error("文件类型不正确");
                }
                String name=index +System.currentTimeMillis()+"." + filetype;
                String path = "\\estimate\\" + name ;
                photoListName.add(path);
                index++;
                File dest = new File(uploadFilePath + path);
                if(!FileUtil.fileUpload(profile,dest,path)){
                    return ActionResult.error("上传失败");
                }
            }
        }
        String photo=null;
        if(photoListName!=null){
            photo=StringUtil.listToString(photoListName);
        }
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        String estimateId="estimateId"+phoneName+System.currentTimeMillis();
        Estimate estimate=new Estimate();
        estimate.setAnonymous(anonymous);
        estimate.setContent(content);
        estimate.setEnable(1);
        estimate.setEstimateId(estimateId);
        estimate.setFoodRecommand(foodRecommond);
        estimate.setGetTime(LocalDateTime.now());
        estimate.setOrderId(orderId);
        estimate.setIntegral(integral);
        estimate.setPhotoList(photo);
        estimate.setScore(score);
        estimate.setUseful(0);
        Integer res=estimateMapper.addEstimate(estimate);
        if(res==1){
            return ActionResult.success("成功");
        }else{
            throw new RuntimeException("save 抛异常了");
            //return ActionResult.error("失败");
        }

    }

    @Override
    public ActionResult getEstimateByShop(Integer shopId, String type, Integer currentPage, Integer size) {

        Page<Map<String,Object>> page=new Page<>(currentPage,size);
        IPage<Map<String,Object>> res_page=null;


        if(type.equals("getTime")){
            res_page= estimateMapper.getEstimateByShop_getTime(shopId,currentPage,size,page);
        }
        else if(type.equals("useful")){
            res_page= estimateMapper.getEstimateByShop_useful(shopId,currentPage,size,page);
        }else if(type.equals("photo")){
            res_page= estimateMapper.getEstimateByShop_photo(shopId,currentPage,size,page);
        }else if(type.equals("goodEs")){
            res_page= estimateMapper.getEstimateByShop_goodEs(shopId,currentPage,size,page);
        }else if(type.equals("badEs")){
            res_page= estimateMapper.getEstimateByShop_badEs(shopId,currentPage,size,page);
        }
        for(Map<String,Object> re:res_page.getRecords()){
            if((Integer)re.get("anonymous")==0){
                re.put("userName","匿名用户");
                re.put("profile","/profile/default.jpeg");
            }
        }
        RespPageBean result=new RespPageBean(res_page.getTotal(),res_page.getRecords());
        return ActionResult.success("获取成功",result);
    }

    @Override
    public ActionResult getEstimateByShopNum(Integer shopId) {
        Map<String,Integer> res=new HashMap();
        res.put("getTime",estimateMapper.getEstimateByShop_getTimeNum(shopId));
        res.put("useful",estimateMapper.getEstimateByShop_usefulNum(shopId));
        res.put("photo",estimateMapper.getEstimateByShop_photoNum(shopId));
        res.put("goodEs",estimateMapper.getEstimateByShop_goodEsNum(shopId));
        res.put("badEs",estimateMapper.getEstimateByShop_badEsNum(shopId));
        return ActionResult.success("获取成功",res);
    }

    @Override
    public ActionResult getTag() {
        List<Map<String,String>> tag=estimateMapper.getTag();
        return ActionResult.success("获取成功",tag);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public ActionResult addUseful(String estimateId) {
        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        Integer res1=estimateMapper.addUseful(estimateId);
        Integer res2=estimateMapper.addUsefulByPhone(phoneName,estimateId,1);
        System.out.println("res1:"+res1+"res2:"+res2);
        if(res1==1&&res2==1)return ActionResult.success("成功");
        throw new RuntimeException("save 抛异常了");
        //return ActionResult.error("失败");
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public ActionResult removeUseful(String estimateId) {

        String phoneName= ((UsersLoginParam) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getPhoneName();
        Integer res1=estimateMapper.subUseful(estimateId);
        Integer res2=estimateMapper.subUsefulByPhone(phoneName,estimateId);
        if(res1==1&&res2==1)return ActionResult.success("成功");
        throw new RuntimeException("save 抛异常了");
        //return ActionResult.error("失败");
    }
}
